#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);

    // 初始化各层对象
    m_serialCore = new SerialPortCore(this);
    m_serialSubject = new SerialPortSubject(m_serialCore);
    m_observer = new SerialPortObserver(m_serialSubject, 3000, this); // 3秒超时
    m_observer2 = new SerialPortObserver(m_serialSubject, 5000, this);

    // 关联业务层信号到UI
    connect(ui->cancelSubscribeBth, &QPushButton::clicked, this, &MainWindow::on_cancelSubscribeBtn_clicked);//TODO 取消订阅改正
    connect(m_observer, &SerialPortObserver::dataUpdated, this, &MainWindow::onDataUpdated);
    connect(m_observer, &SerialPortObserver::subscribeStatusChanged, this, &MainWindow::onSubscribeStatusChanged);
    connect(m_observer, &SerialPortObserver::timeoutOccurred, this, &MainWindow::onTimeoutOccurred);
    connect(m_serialCore, &SerialPortCore::stateChanged, this, &MainWindow::onPortStateChanged);
    connect(m_serialCore, &SerialPortCore::errorOccurred, this, [this](const QString &error) {
        ui->dataDisplay->append("错误: " + error);

        // 关联观察者2的信号（独立处理）
          connect(ui->cancelSubscribeBth, &QPushButton::clicked, this, &MainWindow::on_cancelSubscribeBth2_clicked);//TODO 取消订阅改正
        connect(m_observer2, &SerialPortObserver::dataUpdated, this, &MainWindow::onNewObserverDataUpdated);
            connect(m_observer2, &SerialPortObserver::dataUpdated,this, &MainWindow::on_setSubscribeBtn2_clicked);
            connect(m_observer2, &SerialPortObserver::timeoutOccurred, this, &MainWindow::onNewObserverTimeout);

    });

    // 初始化波特率列表
    ui->baudRateCombo->addItems({"9600","115200"});
    ui->baudRateCombo->setCurrentText("9600");

    // 刷新串口列表
    on_refreshPortsBtn_clicked();
}

MainWindow::~MainWindow() {
    delete m_observer;
    delete m_observer2;
    delete m_serialSubject;
    delete m_serialCore;
    delete ui;
}

void MainWindow::on_refreshPortsBtn_clicked() {
    ui->portNameCombo->clear();
    ui->portNameCombo->addItems(m_serialSubject->getAvailablePorts());
}

void MainWindow::on_openPortBtn_clicked() {
    if (m_serialSubject->isPortOpen()) {
        m_serialSubject->closePort();
        ui->openPortBtn->setText("打开串口");
    } else {
        if (ui->portNameCombo->currentText().isEmpty()) {
            QMessageBox::warning(this, "警告", "请选择串口");
            return;
        }
        bool success = m_serialSubject->openPort(
            ui->portNameCombo->currentText(),
            ui->baudRateCombo->currentText().toInt()
        );
        if (success) {
            ui->openPortBtn->setText("关闭串口");
        }
    }
}

void MainWindow::on_setSubscribeBtn_clicked() {
    int count = ui->setSubscribeBth->value();
    m_observer->setSubscribeCount(count);
    ui->dataDisplay->append(QString("已设置订阅次数: %1").arg(count));
}

void MainWindow::on_cancelSubscribeBtn_clicked() {
    // 添加调试输出，确认函数是否被执行
        qDebug() << "取消订阅按钮被点击，槽函数执行";
        if (m_observer) { // 先检查m_observer是否为空，避免崩溃
                m_observer->cancelSubscribe();
                ui->dataDisplay->append("已取消所有订阅");
            } else {
                qDebug() << "m_observer为空，无法调用cancelSubscribe()";
            }

   // m_observer->cancelSubscribe();
    //ui->dataDisplay->append("已取消所有订阅");
}

void MainWindow::on_sendDataBtn_clicked() {
    QString data = ui->sendDataEdit->text();
    if (data.isEmpty()) return;

    m_observer->sendDataAndSubscribeOnce(data.toUtf8());
    ui->dataDisplay->append(QString("已发送: %1（等待一次响应）").arg(data));
    ui->sendDataEdit->clear();
}

// 显示接收到的数据
void MainWindow::onDataUpdated(const QString &data) {
    ui->dataDisplay->append(data);
}

// 更新订阅状态显示
void MainWindow::onSubscribeStatusChanged(int remainingCount) {
    ui->subscribeStatusLabel->setText(QString("当前剩余订阅次数: %1").arg(remainingCount));
}

// 显示超时信息
void MainWindow::onTimeoutOccurred() {
    ui->dataDisplay->append("超时: 未收到响应");
}
// 新观察者的数据更新处理
void MainWindow::onNewObserverDataUpdated(const QString &data) {
    ui->dataDisplay->append("观察者2数据：" + data); // 在UI上显示新观察者的数据
}
// 新观察者的超时处理
void MainWindow::onNewObserverTimeout() {
    ui
->dataDisplay->append("观察者2超时！"); // 状态栏提示超时
}
// 更新串口状态显示
void MainWindow::onPortStateChanged(bool isOpen) {
   ui->subscribeStatusLabel->setText(QString("串口状态: %1").arg(isOpen ? "已打开" : "未打开"));
}

void MainWindow::on_setSubscribeBtn2_clicked()
{
    int count = ui->setSubscribeBth2->value();
    m_observer->setSubscribeCount(count);
    ui->dataDisplay2->append(QString("已设置订阅次数: %1").arg(count));
}

void MainWindow::on_cancelSubscribeBth2_clicked()
{
    m_observer->cancelSubscribe();
     ui->dataDisplay2->append("已取消所有订阅");
}
